#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>

#include<sys/shm.h>

#include "shm_com.h"

int main(void)
{
    int running = 1;
    void* shared_memory = NULL;
    struct shared_use_st* shared_stuff;
    char buffer[BUFSIZ];
    int shmid;

    shmid = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
    if (-1 == shmid)
    {
        perror("shmget failed\n");
        exit(EXIT_FAILURE);
    }

    shared_memory = shmat(shmid, (void*)0, 0);
    if ((void*)-1 == shared_memory)
    {
        perror("shmat failed\n");
        exit(EXIT_FAILURE);
    }
    printf("memory attached at %p\n", shared_memory);

    shared_stuff = (struct shared_use_st*)shared_memory;
    shared_stuff->written_by_you = 0;
    while(running)
    {
        while (1 == shared_stuff->written_by_you)
        {
            sleep(1);
            printf("waiting for client...\n");
        }

        printf("Enter some text: ");
        fgets(buffer, BUFSIZ, stdin);

        strncpy(shared_stuff->some_text, buffer, TEXT_SZ);
        shared_stuff->written_by_you = 1;

        if (strncmp(buffer, "end", 3) == 0)
        {
            running = 0;
        }
    }

    if (-1 == shmdt(shared_memory))
    {
        perror("shmdt failed\n");
        exit(EXIT_FAILURE);
    }

    return 0;
}
